package com.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.action.UserAction;
import com.bean.MessageBean;
import com.bean.UserBean;
import com.exception.DBException;
import com.exception.UserException;
import com.util.HandleInfo;
import com.util.Regex;
import com.util.StateInfo;

public class UserDeleteServlet extends HttpServlet
{

	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		String userID = request.getParameter("userdeleteid");
		//in order to reload page. present the result of deleting
		String key = request.getParameter("key");
		String value = request.getParameter("value");
		if(null==userID || null == key || null==value)
		{
			HandleInfo.handle(request, response,  
					StateInfo.INNER_CONFIRM_FAIL);
			return;
		}
		if("".equals(userID) || "".equals(key) || "".equals(value))
		{
			HandleInfo.handle(request, response, StateInfo.INNER_CONFIRM_FAIL);
			return;
		}
		if(!"userid".equals(key) && !"firstname".equals(key) && !"lastname".equals(key) && !"typename".equals(key))
		{
			HandleInfo.handle(request, response, StateInfo.INNER_CONFIRM_FAIL);
			return;
		}
		
		if ("userid".equals(key) && !Regex.checkUserID(value))
		{
			HandleInfo.handle(request, response, StateInfo.INNER_CONFIRM_FAIL);
			return;
		}
		// query users by firstname
		else if ("firstname".equals(key) && !Regex.checkName(value))
		{
			HandleInfo.handle(request, response, StateInfo.INNER_CONFIRM_FAIL);
			return;
		}
		//query users by lastname
		else if ("lastname".equals(key) && !Regex.checkName(value))
		{
			HandleInfo.handle(request, response, StateInfo.INNER_CONFIRM_FAIL);
			return;
		}
		//query users by typename
		else if ("typename".equals(key) && !Regex.checkName(value))
		{
			HandleInfo.handle(request, response, StateInfo.INNER_CONFIRM_FAIL);
			return;
		}
		
		
		if(!Regex.checkUserID(userID) || userID.length()!=8)
		{
			HandleInfo.handle(request, response, StateInfo.INNER_CONFIRM_FAIL);
			return;
		}
		
		MessageBean message = new MessageBean();
		message.setKey(key);
		message.setValue(value);
		
		UserBean userBean = new UserBean();
		userBean.setUserID(userID);
		try
		{
			new UserAction().deleteUser(request, response,userBean,message);	
		}
		catch (DBException e)
		{
			HandleInfo.handle(request, response,e.getMessage());
			return;
		}
		catch (UserException e)
		{
			HandleInfo.handle(request, response,e.getMessage());
			return;
		}
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		doGet(request, response);
	}

}
